from django.http import HttpResponse
from django.shortcuts import render
from django.utils import timezone
from myadmin.models import UserDietRecords, Users, DietPlan, SystemNotice


def daily_compliance_detail(request):
    """今日饮食记录详情页"""
    today = timezone.now().date()
    records = UserDietRecords.objects.filter(
        record_time__date=today
    ).select_related('user', 'food').order_by('-record_time')
    
    # 计算初始达标用户数
    compliance_count = records.values('user').distinct().count()
    
    context = {
        'records': records,
        'current_time': timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
        'compliance_count': compliance_count  # 传递计数到模板
    }
    return render(request, 'myadmin/dashboard/daily_compliance_detail.html', context)


def new_users_detail(request):
    """今日新增用户详情"""
    today = timezone.now().date()
    users = Users.objects.filter(
        created_at__date=today
    ).order_by('-created_at')
    
    context = {'users': users}
    return render(request, 'myadmin/dashboard/new_users_detail.html', context)


def pending_diets_detail(request):
    """待处理饮食计划详情"""
    plans = DietPlan.objects.filter(
        is_active=False
    ).select_related('user').order_by('-created_at')
    
    context = {'plans': plans}
    return render(request, 'myadmin/dashboard/pending_diets_detail.html', context)


def system_notices_detail(request):
    """系统通知详情（不使用Q对象）"""
    now = timezone.now()
    
    # 分两次查询后合并结果
    # 1. 永不过期的有效通知
    never_expire = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=True
    )
    
    # 2. 未过期的有效通知
    not_expired = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=False,  # 排除NULL值
        expire_time__gte=now
    )
    
    # 合并结果并排序
    notices = (never_expire | not_expired).order_by('-publish_time')
    
    context = {'notices': notices}
    return render(request, 'myadmin/dashboard/system_notices_detail.html', context)

# 计数接口
def system_notices_count(request):
    """返回系统通知数量（与详情页逻辑一致）"""
    now = timezone.now()
    
    # 1. 永不过期的有效通知
    never_expire_count = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=True
    ).count()
    
    # 2. 未过期的有效通知
    not_expired_count = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=False,  # 排除NULL值
        expire_time__gte=now
    ).count()
    
    # 总通知数 = 永不过期 + 未过期（与详情页保持一致）
    total_count = never_expire_count + not_expired_count
    return HttpResponse(str(total_count))

# 新增其他计数接口（保持数据一致性）
def daily_compliance_count(request):
    """返回今日饮食达标用户数"""
    today = timezone.now().date()
    count = UserDietRecords.objects.filter(
        record_time__date=today
    ).values('user').distinct().count()
    return HttpResponse(str(count))

def new_users_count(request):
    """返回今日新增用户数"""
    today = timezone.now().date()
    count = Users.objects.filter(
        created_at__date=today
    ).count()
    return HttpResponse(str(count))

def pending_diets_count(request):
    """返回待处理饮食计划数"""
    count = DietPlan.objects.filter(
        is_active=False
    ).count()
    return HttpResponse(str(count))
    